/**
 * time: 2025-09-16
 * author: XJ
 * description: 提交验收申请
 */

import { companyReports, companySubmit, uploadFile } from '@/services/apis/companyRegister';
import { UploadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useLocation, useModel, useNavigate } from '@umijs/max';
import { Button, Form, Input, Select, Divider, Rate, Upload, Flex, Space, DatePicker, InputNumber } from 'antd';
import { Col } from 'antd/lib';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
const TextArea = Input.TextArea;
// 统一样式常量，保持与前几页一致
const COMMON_FIELD_STYLE = { width: '100%', height: 40, borderRadius: 4 };
const FORM_LAYOUT = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
  layout: 'horizontal' as const,

  size: 'middle' as const,
};

const StepFourPage: React.FC = (props) => {
  const [form] = Form.useForm();
  const onFinish = (values: any) => { };
  const onFinishFailed = (values: any) => { };
  const { initialState, setInitialState } = useModel('@@initialState');
  const { dataGlobal, setDataGlobal } = useModel('DigitalizationManager.dataGlobal');
  // const [allServices, setAllServices] = useState
  const [evaluationReportList, setEvaluationReportList] = useState<any>([])
  const [auditReportList, setAuditReportList] = useState<any>([])
  const [acceptanceReportList, setAcceptanceReportList] = useState<any>([])
  const [invoiceReportList, setInvoiceReportList] = useState<any[]>([]);
  const [auditDescFilesList, setAuditDescFilesList] = useState<any[]>([]);
  const [paywayFilesList, setPaywayFilesList] = useState<any[]>([]);
  const [otherFilesList, setOtherFilesList] = useState<any[]>([]);
  const [formDisable, setFormDisable] = useState<boolean>(false)
  const [summaryReportList, setSummaryReportList] = useState<any[]>([])
  const location = useLocation();
  const navigate = useNavigate();
  useEffect(() => {
    form.setFieldValue("stepFiveList", dataGlobal.stepFiveData)
    // companyReports({ companyId: dataGlobal.setpThree.companyId, projectId: dataGlobal.setpThree.projectId }).then(res => {
    //   const { code, data } = res;
    //   if (code == "0") {
    //     debugger
        const {
          auditReport = [],
          evaluationReport = [],
          acceptanceReport = [],
          invoiceReport = [],
          summaryReport = [],
          auditDescFiles = [],
          paywayFiles = [],
          otherFiles = []
        } = dataGlobal.fiveDataAll || {};
        setFormDisable(dataGlobal.fiveDataAll && dataGlobal.fiveDataAll?.edit == "1")
        form.setFieldsValue({ ...dataGlobal.fiveDataAll, auditReport, evaluationReport, acceptanceReport })
        setEvaluationReportList(evaluationReport?.map((item: any) => ({ name: item.filename, uid: Math.random().toString() })))
        setAuditReportList(auditReport?.map((item: any) => ({ name: item.filename, uid: Math.random().toString() })))
        setAcceptanceReportList(acceptanceReport?.map((item: any) => ({ name: item.filename, uid: Math.random().toString() })))
        setInvoiceReportList(invoiceReport?.map((item: any) => ({ name: item.filename, uid: Math.random().toString() })))
        setAuditDescFilesList(auditDescFiles?.map((item: any) => ({ name: item.filename, uid: Math.random().toString() })))
        setPaywayFilesList(paywayFiles?.map((item: any) => ({ name: item.filename, uid: Math.random().toString() })))
        setOtherFilesList(otherFiles?.map((item: any) => ({ name: item.filename, uid: Math.random().toString() })))
        setSummaryReportList(summaryReport?.map((item: any) => ({ name: item.filename, uid: Math.random().toString() })))
    //   }
    // })
  }, [dataGlobal.stepFiveData])

  const companySubmitFun = () => {
    form.validateFields().then(values => {
      companySubmit({
        ...values, companyId: dataGlobal.setpThree.companyId,
        projectId: dataGlobal.setpThree.projectId
      }).then(res => {
        const { code } = res;
        if (code == "0") {
          navigate("/api_status_page", {
            state: {
              title: "项目验收",
              message: "项目验收提交成功",
              callbackUrl: location.pathname
            }
          });
        } else {
          navigate("/api_status_page", {
            state: {
              title: "项目验收",
              message: "项目验收提交失败",
              callbackUrl: location.pathname
            }
          });
        }
      })
    })

  }

  const handleAutoUpload = async (file: any, formPath: any) => {

    try {
      const response = await uploadFile(file)
      if (response.code == "0") {

        setSummaryReportList(prev => ([{ name: response.data.filename, uid: Math.random().toString() }]))
        form.setFieldValue(formPath, [response.data])

      }
    } catch (error) {
    }
  };

  return (
    <div
      style={{
        padding: '20px',
        boxSizing: 'border-box',
        backgroundColor: '#f8f9fa',
        height: '100%',
        overflow: 'hidden',
      }}
    >
      <div
        style={{
          backgroundColor: '#fff',
          padding: '20px',
          borderRadius: 8,
          boxShadow: '0 1px 3px rgba(0,0,0,0.05)',
          height: '100%',
          overflowY: 'auto',
        }}
      >
        <Form
          disabled={!(dataGlobal.stepTwoDisabled && dataGlobal.stepThreeDisabled) || formDisable}
          form={form} {...FORM_LAYOUT} onFinish={onFinish} onFinishFailed={onFinishFailed}>
          {/* 数字化与维度信息组 */}
          <div style={{ marginBottom: 24 }}>
            <h3
              style={{
                fontSize: 16,
                fontWeight: 500,
                color: '#1f2937',
                marginBottom: 12,
              }}
            >
              数字化改造成效
            </h3>
            <Form.Item
              label="评测时间"
              name={"rateTime"}
              rules={[{ required: true, message: '请选择评测时间' }]}
              style={{ marginBottom: 20 }}
              getValueProps={(value) => ({ value: value && dayjs(value) })}
              normalize={(value) => value && `${dayjs(value).format("YYYY-MM-DD HH:mm:ss")}`}
            >
              <DatePicker disabled placeholder='评测机构未填写' />
            </Form.Item>
            <Form.Item label="数字化水平等级(改造后)" style={{ marginBottom: 20 }}>

              <Space.Compact style={{ width: '100%' }}>  {/* 补充布局容器，避免按钮错位 */}
                <Form.Item
                  name="digitalLevel"  // 保持原name
                  rules={[{ required: true, message: '请选择数字化水平等级' }]}
                  noStyle
                >
                  <Select
                    disabled
                    style={{ ...COMMON_FIELD_STYLE, width: '90%' }}
                    placeholder="待评测机构填写"
                    // 绑定表单值（与name对应）
                    value={form.getFieldValue('digitalLevel')}
                    onChange={(value) => form.setFieldValue('digitalLevel', value)}
                  >
                    {/* <Select.Option value="none">无等级</Select.Option> */}
                    <Select.Option value="level1">一级</Select.Option>
                    <Select.Option value="level2">二级</Select.Option>
                    <Select.Option value="level3">三级</Select.Option>
                    <Select.Option value="level4">四级</Select.Option>
                  </Select>
                </Form.Item>
                <Button
                  style={{ ...COMMON_FIELD_STYLE, width: '10%' }}
                  onClick={() =>
                    window.open(
                      'https://ucenter.miit.gov.cn/login.jsp?toUrl=http%3A%2F%2Fzjtx.miit.gov.cn%2Fqyxx%2Fgotoszhsp',
                    )
                  }
                  type="primary"
                >
                  去测试
                </Button>
              </Space.Compact>

            </Form.Item>
            <Form.Item
              name="effect"
              label="数字化基础、管理及成效得分"
              rules={[{ required: true, message: '请输入数字化基础、管理及成效得分', pattern: /^\d+(\.\d+)?$/ }]}
              style={{ marginBottom: 20 }}
            >
              <Input placeholder='评测机构未填写' disabled style={COMMON_FIELD_STYLE} />
            </Form.Item>

            <Form.Item
              label="审计时间"
              name={"auditTime"}
              rules={[{ required: true, message: '请选择审计时间' }]}
              style={{ marginBottom: 20 }}
              getValueProps={(value) => ({ value: value && dayjs(value) })}
              normalize={(value) => value && `${dayjs(value).format("YYYY-MM-DD HH:mm:ss")}`}
            >
              <DatePicker disabled placeholder='审计机构未填写' />
            </Form.Item>
            <Form.Item
              name="transformationInvestment"
              label="改造总花费(万元)"
              rules={[{ required: true, message: '请输入改造总花费', pattern: /^\d+(\.\d+)?$/ }]}
              style={{ marginBottom: 20 }}
            >
              <Input disabled placeholder='审计机构未填写' style={COMMON_FIELD_STYLE} />
            </Form.Item>
            <Form.Item
              label="软件投入"
              name="softwareInvestment"
              rules={[{ required: true, message: '请输入软件投入' }]}
              style={{ marginBottom: 20 }}
            >
              <InputNumber disabled placeholder='审计机构未填写' style={COMMON_FIELD_STYLE} />
            </Form.Item>

            <Form.Item
              label="云服务投入"
              name="cloudInvestment"
              rules={[{ required: true, message: '请输入云服务投入' }]}
              style={{ marginBottom: 20 }}
            >
              <InputNumber disabled placeholder='审计机构未填写' style={COMMON_FIELD_STYLE} />
            </Form.Item>
            <Form.Item
              label="设备投入"
              name="deviceInvestment"
              rules={[{ required: true, message: '请输入设备投入' }]}
              style={{ marginBottom: 20 }}
            >
              <InputNumber disabled placeholder='审计机构未填写' style={COMMON_FIELD_STYLE} />
            </Form.Item>

            <Form.Item
              name="innovationDimension"
              label="创新维度"
              rules={[{ required: true, message: '请输入创新维度' }]}
              style={{ marginBottom: 20 }}
            >
              <TextArea
                maxLength={500}
                placeholder={`1.研发经费占营业收入比例（%）
2.关键工序数控化率（%）
3.数字化研发设计工具普及率（%）
4.设备联网率（%）
5.新产品产值率（%）
6.设备数字化率（%）
7.协同研发平台覆盖率（%）
8.新产品研制周期（天）`}
                showCount
                style={{
                  minHeight: 100,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="capacityDimension"
              label="市场维度"
              rules={[{ required: true, message: '请输入市场维度' }]}
              style={{ marginBottom: 20 }}
            >
              <TextArea
                maxLength={500}
                placeholder={`1.销售额（万元）
2.主营产品市场占有率（%）
3.线上交易增长率（%）`}
                showCount
                style={{
                  minHeight: 100,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="qualityDimension"
              label="提质维度"
              rules={[{ required: true, message: '请输入提质维度' }]}
              style={{ marginBottom: 20 }}
            >
              <TextArea
                maxLength={500}
                showCount
                placeholder={`1.平均核心产品合格率（%）
2.月度平均产品合格率（%）
3.预测性维护准确率（%）
4.智能检测覆盖率（%）
`}
                style={{
                  minHeight: 100,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="sampleDimension"
              label="降本维度"
              rules={[{ required: true, message: '请输入降本维度' }]}
              style={{ marginBottom: 20 }}
            >
              <TextArea
                maxLength={500}
                placeholder={`1.生产成本（万元）
2.管理成本（万元）
3.采购成本（万元）
4.研发成本（万元）
5.能耗成本（万元）
`}
                showCount
                style={{
                  minHeight: 100,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="efficiencyDimension"
              label="增效维度"
              rules={[{ required: true, message: '请输入增效维度' }]}
              style={{ marginBottom: 20 }}
            >
              <TextArea
                maxLength={500}
                showCount
                placeholder={`1.全员劳动生产率（%）
2.销售订单准时交货率（%）
3.采购订单准时交货率（%）
4.生产计划达成率（%）
5.产能利用率（%）
6.库存周转天数（天）
7.库存周转率（%）
8.工单处理时效（h）

`}
                style={{
                  minHeight: 100,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="greenDimension"
              label="绿色维度"
              rules={[{ required: true, message: '请输入绿色维度' }]}
              style={{ marginBottom: 20 }}
            >
              <TextArea
                maxLength={500}
                showCount
                placeholder={`
1.废水排放量（t/d）
2.废气排放量（m³/y）
3.单位产值综合能耗（吨标准煤/万元）
`}
                style={{
                  minHeight: 100,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="safetyDimension"
              label="安全维度"
              rules={[{ required: true, message: '请输入安全维度' }]}
              style={{ marginBottom: 20 }}
            >
              <TextArea
                maxLength={500}
                placeholder={`1.事故率（%）
2.安全培训合格率（%）
3.安全漏洞修复时效（h）
`}
                showCount
                style={{
                  minHeight: 100,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>

            <Form.Item
              name="otherDimension"
              label="其他维度"
              rules={[{ required: true, message: '请输入其他维度' }]}
              style={{ marginBottom: 20 }}
            >
              <TextArea
                maxLength={500}
                placeholder="请尽量用若干定量指标描述"
                showCount
                style={{
                  minHeight: 100,
                  resize: 'vertical',
                  ...COMMON_FIELD_STYLE,
                }}
              />
            </Form.Item>
          </div>

          <Divider />

          {/* 服务与售后信息组 */}
          <div style={{ marginBottom: 24 }}>
            <h3
              style={{
                fontSize: 16,
                fontWeight: 500,
                color: '#1f2937',
                marginBottom: 12,
              }}
            >
              对所使用数字化服务商及评价
            </h3>
            <Form.List
              name="stepFiveList"
            >
              {(fields) => (
                <>
                  {fields.map((field, index) => (
                    <div
                      key={field.key}
                      style={{
                        border: '1px solid #eee',
                        padding: 16,
                        borderRadius: 4,
                        marginBottom: 16
                      }}
                    >

                      <Form.Item
                        {...field}
                        name={[field.name, 'dealWayName']}
                        label="产品以及解决方案名称"
                        rules={[{ required: true, message: '请输入产品以及解决方案名称' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <Input style={COMMON_FIELD_STYLE} />
                      </Form.Item>

                      <Form.Item
                        {...field}
                        name={[field.name, 'connectProvider']}
                        label="关联服务商"
                        rules={[{ required: true, message: '请输入关联服务商' }]}
                        style={{ marginBottom: 20 }}
                      >
                        <Input style={COMMON_FIELD_STYLE} />
                      </Form.Item>

                      <Form.Item
                        {...field}
                        name={[field.name, 'evaluationScore']}
                        label="评价星数"
                        rules={[{ required: true, message: '请选择评价星数' }]}
                        style={{ marginBottom: 20 }}
                        initialValue={5}
                      >
                        <Rate />
                      </Form.Item>

                      <Form.Item
                        {...field}
                        name={[field.name, 'totalScore']}
                        label="服务商评价总星级"
                        rules={[{ required: true, message: '请选择服务商评价总星级' }]}
                        style={{ marginBottom: 20 }}
                        initialValue={5}
                      >
                        <Rate />
                      </Form.Item>
                    </div>
                  ))}
                </>
              )}
            </Form.List>
          </div>

          <Divider />

          {/* 报告信息组 */}
          <div style={{ marginBottom: 24 }}>
            <h3
              style={{
                fontSize: 16,
                fontWeight: 500,
                color: '#1f2937',
                marginBottom: 12,
              }}
            >
              附件材料
            </h3>

            <Form.Item
              name="evaluationReport"
              label="等级评测证明"
              rules={[{ required: true, message: '请输入等级评测证明' }]}
              style={{ marginBottom: 20 }}
            >
              <Upload disabled fileList={evaluationReportList}>
                {evaluationReportList?.length == 0 || !evaluationReportList && "机构未上传"}
              </Upload>
            </Form.Item>

            <Form.Item
              name="auditReport"
              label="审计报告"
              rules={[{ required: true, message: '请输入审计报告' }]}
              style={{ marginBottom: 20 }}
            >
              <Upload disabled fileList={auditReportList}>
                {auditReportList?.length == 0 || !auditReportList && "机构未上传"}
              </Upload>
            </Form.Item>

            <Form.Item
              name="invoiceReport"
              label="发票"
              rules={[{ required: true, message: '请输入发票' }]}
              style={{ marginBottom: 20 }}
            >
              <Upload
                fileList={invoiceReportList}
                disabled
              >
                {invoiceReportList?.length == 0 || !invoiceReportList && "机构未上传"}
              </Upload>
            </Form.Item>

            <Form.Item
              name="auditDescFiles"
              label="审计情况说明"
              rules={[{ required: true, message: '请输入审计情况说明' }]}
              style={{ marginBottom: 20 }}
            >
              <Upload
                fileList={auditDescFilesList}
                disabled
              >
                {auditDescFilesList?.length == 0 || !auditDescFilesList && "机构未上传"}
              </Upload>
            </Form.Item>

            <Form.Item
              name="paywayFiles"
              label="付款凭证"
              rules={[{ required: true, message: '请输入付款凭证' }]}
              style={{ marginBottom: 20 }}
            >
              <Upload
                fileList={paywayFilesList}
                disabled
              >
                {paywayFilesList?.length == 0 || !paywayFilesList && "机构未上传"}
              </Upload>
            </Form.Item>

            <Form.Item
              name="otherFiles"
              label="其他文件"
              style={{ marginBottom: 20 }}
            >
              <Upload
                fileList={otherFilesList}
                disabled
              >
                {otherFilesList?.length == 0 || !otherFilesList && "机构未上传"}
              </Upload>
            </Form.Item>

            <Form.Item
              name="summaryReport"
              label="企业提交总结报告"
              rules={[{ required: true, message: '请输入企业提交总结报告' }]}
              style={{ marginBottom: 20 }}
            >
              <Upload
                disabled={!(evaluationReportList && evaluationReportList.length != 0
                  && auditReportList && auditReportList.length != 0
                  && invoiceReportList && invoiceReportList.length != 0
                  && auditDescFilesList && auditDescFilesList.length != 0
                  && paywayFilesList && paywayFilesList.length != 0
                  && otherFilesList && otherFilesList.length != 0
                )
                }
                fileList={summaryReportList}
                beforeUpload={(file) => {
                  handleAutoUpload(file, "summaryReport");
                  return false;
                }}
                listType="text"
                maxCount={1}
              >
                <Button disabled={!(evaluationReportList && evaluationReportList.length != 0
                  && auditReportList && auditReportList.length != 0)} icon={<UploadOutlined />}>上传总结报告</Button>
              </Upload>
            </Form.Item>
            <Form.Item
              name="acceptanceReport"
              label=" 验收报告"
              // rules={[{ required: true, message: '请输入验收报告' }]}
              style={{ marginBottom: 20 }}
            >
              <Upload disabled fileList={acceptanceReportList}>
                {acceptanceReportList?.length == 0 || !acceptanceReportList && "机构未上传"}
              </Upload>
            </Form.Item>
          </div>

          {/* 提交按钮 */}
          <Form.Item label={null} style={{ marginTop: 40, textAlign: 'center' }}>
            <Button onClick={companySubmitFun} style={{}} type="primary" >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default StepFourPage;
